<template>
  <view class="jinuns">
    <BaNner :banner_img="ban_img"/>
    <!-- 栏目 -->
    <view class="column">
      <u-tabs name="name" :list="good_sort" :is-scroll="false" :current="current" @change="change"
        :bg-color="'background: #F2F2F2;'" :inactive-color="'#10100E;'" :active-color="'#23AC38'" :font-size="34"
        :border-radius="'18'" :show-bar="true">
      </u-tabs>
    </view>
    
    <!-- 加载状态 -->
<!--    <view class="loading-mask" v-if="isLoading">
      <view class="loading-spinner">
        <view class="spinner-circle"></view>
        <view class="spinner-text">加载中...</view>
      </view>
    </view> -->
    
    <!-- 内容区域 -->
    <view class="content-container">
      <!-- <view class="titiels" > {{BrandList[0].title}}</view> -->
      
      <!-- 品牌活动 -->
      <view class="pphd animate-fade-in" v-if="current === 0" style="width: 100%;">
        <u-parse :html="item.content" v-for="(item,index) in BrandList" :key="index"></u-parse>
      </view>
      
      <!-- 粉丝建议解答 -->
      <view class="lbs animate-fade-in" v-if="current === 1">
        <view class="userlist" v-for="(item,index) in fxlist" :key="index" @click="Navigator(item.content,item.wenti)">
          <view class="name">{{item.wenti}}</view>
          <view class="name">{{item.miaoshu}}</view>
        </view>
      </view>
      
      <!-- 视频列表 -->
      <view class="video-container animate-fade-in" v-if="current === 2">
        <view class="zd_viode" v-if="voldlist.length > 0">
          <video :id="'video_' + 0" 
                 :src="'https://img.ukh5.com' + voldlist[0].file" 
                 @error="videoErrorCallback"
                 :danmu-list="danmuList" 
                 controls 
                 :poster="'https://img.ukh5.com' + voldlist[0].image"
                 @play="handlePlay(0)" 
                 @pause="handlePause(0)"
                 @ended="handleEnded(0)">
          </video>
          <view class="v_title">
            <view class="name">{{voldlist[0].title}}</view>
            <view class="icon">
              <image src="/static/home/yj.png" mode="widthFix"></image>
              <view>{{voldlist[0].pv}}</view>
            </view>
          </view>
          <view class="tps">{{voldlist[0].describe}}</view>
        </view>
        
        <view class="v_list">
          <view class="list_itme animate-scale-in" v-for="(item, index) in voldlist" :key="index" v-if="index > 0">
            <video :id="'video_' + index" 
                   :src="'https://img.ukh5.com' + item.file" 
                   @error="videoErrorCallback"
                   :danmu-list="danmuList" 
                   controls 
                   :poster="'https://img.ukh5.com' + item.image"
                   @play="handlePlay(index)" 
                   @pause="handlePause(index)"
                   @ended="handleEnded(index)">
            </video>
            <view class="v_title">
              <view class="name">{{item.title}}</view>
              <view class="icon">
                <image src="/static/home/yj.png" mode="widthFix"></image>
                <view>{{item.pv}}</view>
              </view>
            </view>
            <view class="tps">{{item.describe}}</view>
          </view>
        </view>
        
        <!-- 加载更多提示 -->
        <view class="load-more" v-if="showLoadMore">
          <view class="loading-text">加载更多...</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { brand_list, faq_list, video_list , product_banner  } from '@/core/api/index.js'
export default {
  data() {
    return {
      good_sort: [
        { name: '品牌活动' },
        { name: '粉丝建议解答' },
        { name: '企业宣传视频' }
      ],
      current: 0,
      voldlist: [],
      playingIndex: -1,
      isLoading: false,
      ban_img: '',
      BrandList: [],
      fxlist: [],
      Faqlis_page: 1, // 分页从1开始
      Faqlis_pageSize: 10,
      jupage: 1, // 分页从1开始
      jupageSize: 10,
      hasMoreVideos: true, // 是否还有更多视频
      showLoadMore: false, // 是否显示加载更多提示
      isLoadingMore: false // 是否正在加载更多
    }
  },
  onLoad() {
    this.loadInitialData()
  },
  onReachBottom() {
    // 当滚动到底部时，加载更多内容
    if (this.current === 2 && this.hasMoreVideos && !this.isLoadingMore) {
      this.loadMoreVideos()
    }
  },
  methods: {
    Navigator(conton, wenti) {
      uni.navigateTo({
        url: `/pages/wdatali?con=${conton}&title=${wenti}`
      })
    },
    
    async loadInitialData() {
      try {
        this.isLoading = true
        
        // 并行加载数据
        const [bannerData, brandData, faqData, videoData] = await Promise.all([
          product_banner(),
          brand_list(),
          faq_list({ page: this.Faqlis_page, pageSize: this.Faqlis_pageSize }),
          video_list({ categoryId: null, page: this.jupage, pageSize: this.jupageSize })
        ])
        
        // 处理banner数据
        bannerData._data.list.forEach(res => {
          if (res.name === '品牌中心') {
            this.ban_img = res.image
          }
        })
        
        // 处理品牌活动数据
        this.BrandList = brandData._data.list
        
        // 处理粉丝建议解答数据
        this.fxlist = faqData._data.list
        
        // 处理视频数据
        this.voldlist = videoData._data.list
        this.hasMoreVideos = videoData._data.list.length >= this.jupageSize
        
      } catch (error) {
        console.error('加载初始数据失败:', error)
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    async change(index) {
      console.log('切换栏目:', index)
      
      // 如果切换到已加载过的栏目，不需要重新加载数据
      if (this.current === index) return
      
      this.current = index
      this.playingIndex = -1
      
      // 如果是切换到视频栏目且数据为空，则加载视频数据
      if (index === 2 && this.voldlist.length === 0) {
        await this.loadVideos()
      }
    },
    
    async loadVideos() {
      try {
        this.isLoading = true
        const data = await video_list({ 
          categoryId: null, 
          page: this.jupage, 
          pageSize: this.jupageSize 
        })
        
        this.voldlist = data._data.list
        this.hasMoreVideos = data._data.list.length >= this.jupageSize
        
      } catch (error) {
        console.error('获取视频列表失败:', error)
        uni.showToast({
          title: '视频加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    async loadMoreVideos() {
      try {
        this.isLoadingMore = true
        this.showLoadMore = true
        
        const nextPage = this.jupage + 1
        const data = await video_list({ 
          categoryId: null, 
          page: nextPage, 
          pageSize: this.jupageSize 
        })
        
        if (data._data.list.length > 0) {
          this.voldlist = [...this.voldlist, ...data._data.list]
          this.jupage = nextPage
          this.hasMoreVideos = data._data.list.length >= this.jupageSize
        } else {
          this.hasMoreVideos = false
          uni.showToast({
            title: '没有更多视频了',
            icon: 'none'
          })
        }
        
      } catch (error) {
        console.error('加载更多视频失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoadingMore = false
        this.showLoadMore = false
      }
    },
    
    handlePlay(index) {
      console.log(`播放视频 ${index}，当前播放索引: ${this.playingIndex}`)
      
      // 先暂停其他视频
      if (this.playingIndex !== -1 && this.playingIndex !== index) {
        this.pauseVideo(this.playingIndex)
      }
      
      // 设置当前播放索引
      this.playingIndex = index
      
      // 延迟播放，确保DOM已更新
      this.$nextTick(() => {
        const videoContext = uni.createVideoContext(`video_${index}`)
        videoContext.play()
        console.log(`视频 ${index} 开始播放`)
      })
    },
    
    handlePause(index) {
      console.log(`暂停视频 ${index}，当前播放索引: ${this.playingIndex}`)
      if (this.playingIndex === index) {
        this.playingIndex = -1
      }
    },
    
    handleEnded(index) {
      console.log(`视频 ${index} 播放结束`)
      this.playingIndex = -1
      
      // 自动播放下一个视频
      if (index < this.voldlist.length - 1) {
        this.handlePlay(index + 1)
      }
    },
    
    pauseVideo(index) {
      console.log(`尝试暂停视频 ${index}`)
      const videoContext = uni.createVideoContext(`video_${index}`)
      videoContext.pause()
    },
    
    videoErrorCallback(e) {
      console.log('视频加载错误:', e)
      uni.showToast({
        title: '视频加载失败',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.jinuns {
  .login {
    width: 100%;
    image {
      width: 100%;
      height: auto;
    }
  }
}

.column {
  width: 100%;
  padding: 0 20rpx 0 0;
}

.titiels {
  font-size: 40rpx;
  font-weight: bold;
  text-align: center;
  margin: 36rpx 0 auto;
}

.lbs {
  padding: 40rpx 20rpx;
}

.userlist {
  margin-bottom: 30rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #efe9e9;
  font-size: 28rpx;
  color: #666666;
  view:nth-child(1) {
    color: #000;
    font-size: 34rpx;
    font-weight: 700;
    margin-bottom: 10rpx;
  }
}

.zd_viode,
.v_list {
  width: 100%;
  padding: 32rpx 30rpx 26rpx;
  video {
    width: 100%;
    height: 378rpx;
    border-radius: 20rpx;
  }
  .v_title {
    display: flex;
    margin-top: 15rpx;
    width: 100%;
    justify-content: space-between;
    .name {
      font-weight: 700;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-top: 5rpx;
      width: 600rpx;
      font-size: 34rpx;
      color: #000000;
    }

    .icon {
      display: flex;
      color: #666666;
      font-size: 24rpx;
      align-items: center;
      image {
        width: 28rpx;
        margin-right: 10rpx;
        height: auto;
      }
    }
  }

  .tps {
    font-size: 28rpx;
    color: #666666;
    margin-top: 10rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 5rpx;
    width: 720rpx;
  }
}

.v_list {
  padding: 0 30rpx 40rpx;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  .list_itme {
    width: 49%;
    margin-bottom: 20rpx;
    video {
      height: 200rpx;
    }

    .v_title {
      .name {
        font-weight: 400;
        font-size: 30rpx;
        width: 300rpx;
        color: #1D2129;
      }
    }

    .tps {
      font-size: 24rpx;
      color: #666666;
      width: 350rpx;
    }
  }
}

/* 加载动画 */
.loading-mask {
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner-circle {
  width: 80rpx;
  height: 80rpx;
  border: 8rpx solid #23AC38;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.spinner-text {
  font-size: 30rpx;
  color: #23AC38;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 内容区域动画 */
.animate-fade-in {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.animate-scale-in {
  animation: scaleIn 0.3s ease-out;
}

@keyframes scaleIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}

/* 加载更多提示 */
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}
</style>